package com.q3d.demo.common.lib.service.response;

import org.springframework.http.ResponseEntity;

import com.alibaba.fastjson2.JSONObject;
import com.q3d.demo.common.lib.service.exception.ServiceException;

import lombok.extern.slf4j.Slf4j;

@Slf4j /** Lombok 的 Logger 注解 */
/**
 * @author 叶湘 ( weixin:yexiang841, email:yexiang841@qq.com )
 */
public class ResponseUtil {

    public static <DTO> DTO parseResponse(Class<DTO> dtoClass, ResponseEntity<JSONObject> response,
            String remoteSvcName) {
        if (response == null) {
            throw new ServiceException(ResponseStatus.INTERNAL_SERVER_ERROR,
                    "Response_Got_Null_From: " + remoteSvcName);
        }
        JSONObject responseBody = response.getBody();
        return ResponseUtil.parseResponseBody(dtoClass, responseBody);
    }

    public static <DTO> DTO parseResponseBody(Class<DTO> dtoClass, JSONObject responseBody) {
        log.debug(responseBody.toString());
        int code = responseBody.getInteger("code");
        String message = responseBody.getString("message");
        // 审核 status.code
        if (code != ResponseStatus.OK.getCode()) {
            throw new ServiceException(ResponseStatus.INTERNAL_SERVER_ERROR, message);
        }
        JSONObject data = responseBody.getJSONObject("data");
        // 审核 data
        if (data == null) {
            return null;
        }
        // 请求正常，尝试转换为 DTO 对象返回
        DTO dto = data.to(dtoClass);
        return dto;
    }

}
